package csu.softwaremetric.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class CodeUploadService {
    public JSONObject uploadCode(MultipartFile code)
    {
        JSONObject json = new JSONObject();
        try {
            if(code == null){
                json.put("STATUS", "FAILURE");
                json.put("MSG", "上传的代码为null，上传失败");
                return json;
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String newName = sdf.format(new Date()) + "-" + code.getOriginalFilename();
            String resourcesPath = System.getProperty("user.dir");
            String fileName = "/upload/Code/" + newName;

            File targetFile = new File(resourcesPath, fileName);
            if(!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdirs();
            }

            code.transferTo(targetFile);

            json.put("STATUS", "SUCCESS");
            json.put("MSG", "上传成功");
            json.put("FILENAME", newName);
            return json;
        } catch (IOException e) {
            json.put("STATUS", "ERROR");
            json.put("MSG", "系统异常，上传失败");
            return json;
        }
    }
}
